import axios from "axios";

import Router from '../router/index.js';


// import store from '@/store'

import {
  MessageBox,
  Message
} from "element-ui";
import store from "@/store";
import Qs from "qs";
import {
  getToken,
  getUserid
} from "@/utils/auth";


var _this = this
var host = window.location.host;
// console.log("host", host)
// create an axios instance
const service = axios.create({
  // baseURL: ''+'sapi/',
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  withCredentials: true, // send cookies when cross-domain requests
  timeout: 50000 // request timeout
});



// request interceptor
service.interceptors.request.use(
  config => {
    // config.data.token = ''
    if (store.getters.token) {
      // console.log(config.data, store.getters.token, store.getters.userid, '----')
      config.headers["Authorization"] = "Bearer " + getToken();
      if (!config.data) {
        config.data = {}
      }
      // config.data = config.data || {}
      var p = {
        token: getToken(),
        userid: getUserid(),
        backend: 1,
      }
      // console.log('-11-', config.data)
      Object.assign(config.data, p);

      // config.headers['Admin-Token'] = getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
    }

    // 打印机参数
    const print_info = localStorage ? localStorage.getItem("print_info") : "";
    if (print_info) {
      config.headers["PrinterDevice"] = print_info;
    }

    if (config.method == "get") {
      Object.assign(config.params, config.data);
    }
    if (config.method === "post" || config.method === "put") {
      config.data = Qs.stringify(config.data);
    }
    return config;
  },
  error => {
    // Do something with request error
    console.log(error); // for debug
    Promise.reject(error);
  }
);

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data;
    // console.log('-----', res)
    // if the custom code is not 20000, it is judged as an error.
    if (Number(res.status) !== 200) {
      Message({
        message: res.message || "Error",
        type: "error",
        duration: 5 * 1000
      });
      if(Number(res.status) === 201 && res.message == 'Token错误'){
        // console.log('3333',_this, Router, location.href)
        setTimeout(() => {
          store.dispatch('user/logout').then(() => {
            location.reload(true)
          })
        }, 3000)
      }
      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (
        res.status * 1 === 401 ||
        res.statusCode * 1 === 401 ||
        res.data.status * 1 == 401
      ) {
        // to re-login
        MessageBox.confirm(
          "您已经登出，您可以取消停留在此页面，或再次登录",
          "确认注销", {
            confirmButtonText: "注销",
            cancelButtonText: "取消",
            type: "warning"
          }
        ).then(() => {
          store.dispatch("user/resetToken").then(() => {
            location.reload();
          });
        });
      }
      return Promise.reject(res);
    } else {
      return res;
    }
  },
  error => {
    console.log("err" + error); // for debug
    Message({
      message: error.message,
      type: "error",
      duration: 5 * 1000
    });
    return Promise.reject(error);
  }
);

export default service;
